#include"common.h"
#include"Socket.h"


Socket::Socket(std::string ip, uint16_t port):_ip(ip), _port(port)
{
    _sockfd = socket(AF_INET, SOCK_STREAM, 0);
    myAssert(_sockfd != -1, "sock error");
}

int Socket::GetFd() { return _sockfd; }

void Socket::Bind()
{
    struct sockaddr_in serv_addr;
    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = _ip == "" ? INADDR_ANY : inet_addr(_ip.c_str());
    serv_addr.sin_port = htons(_port);
    myAssert(bind(_sockfd, (sockaddr *)&serv_addr, sizeof(serv_addr)) != -1, "bind error");
}

void Socket::Listen()
{
    myAssert(listen(_sockfd, SOMAXCONN) != -1, "listen error");
}

int Socket::Accept()
{
    struct sockaddr_in cli_addr;
    bzero(&cli_addr, sizeof(cli_addr));
    socklen_t len = sizeof(cli_addr);
    int cli_fd = accept(_sockfd, (sockaddr *)&cli_addr, &len);
    myAssert(cli_fd != -1, "accept error");
    printf("new client connect client_fd: %d IP: %s port: %d\n",
            cli_fd, inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port));

    return cli_fd;
}
void Socket::Connect()
{
    struct sockaddr_in server_addr;
    bzero(&server_addr, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(_ip.c_str());
    server_addr.sin_port = htons(_port);
    myAssert(connect(_sockfd, (sockaddr *)&server_addr, sizeof(server_addr))!=-1,"client connect error");
}
Socket::~Socket()
{
    close(_sockfd);
}

